package cn.touna.jss.modules.third.chaboshi;

import cn.touna.risk.api.enums.SystemErrorCodeEnum;
import cn.touna.jss.common.exception.ResponseException;
import cn.touna.jss.common.factory.ResponseFactory;
import cn.touna.jss.common.properties.disconf.ChaboshiProperties;
import cn.touna.jss.common.util.ValidUtil;
import cn.touna.jss.modules.adapter.ApiMapping;
import cn.touna.jss.modules.custom.cheyiping.dto.MaintenanceRecordRequest;
import cn.touna.jss.modules.custom.cheyiping.utils.CheyipingUtil;
import cn.touna.risk.api.domain.Response;
import cn.touna.risk.cache.redis.RedisCache;
import com.alibaba.fastjson.JSONObject;
import com.chaboshi.util.CBS;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.concurrent.TimeUnit;

@Service
public class ChaboshiService {

    @Autowired
    private ChaboshiProperties config;

    @Autowired
    private RedisCache redisCache;

    private static final Logger logger = LogManager.getLogger();

    /**
     * 购买报告，返回orderId<br/>
     * 如果失败，抛出异常信息
     * @param vin
     * @param callbackurl
     * @param engineno
     * @param licenseplate
     * @return
     * @throws Exception
     */
    private String buyReport(String vin,String callbackurl,String engineno,String licenseplate)throws ResponseException{
        String res = CBS.getInstance( config.getUserId(),config.getKeySecret())
                .getBuyReport(vin, engineno,licenseplate, callbackurl);
        JSONObject resObj = JSONObject.parseObject(res);
        String code = resObj.getString("Code");
        if("0".equals(code)){
            return resObj.getString("orderId");
        }
        String msg = resObj.getString("Message");
        throw new ResponseException(ResponseFactory.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_FAIL,msg));
    }

    public Response buyReport(MaintenanceRecordRequest request){
        try{
            String orderId = buyReport(request.getVin(),"",request.getEngineNo(),request.getPlateNo());
            return ResponseFactory.success(orderId);
        }catch (ResponseException se){
            return se.getResponse();
        }catch (Exception e){
            return ResponseFactory.fail(SystemErrorCodeEnum.JSS_SYSTEM_ERROR,e.getMessage());
        }
    }

    public Response getReportData(@RequestParam("orderId") String orderId){
        String res  = CBS.getInstance(config.getUserId(),config.getKeySecret() ). getNewReportJson(orderId);
        JSONObject resObj = JSONObject.parseObject(res);
        String code = resObj.getString("Code");
        if("1104".equals(code)){
            return ResponseFactory.success(resObj);
        }
        return ResponseFactory.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR,resObj.getString("Message"),resObj);
    }

    @ApiMapping(value = "chaboshi.getReport",desc = "查博士.查询报告")
    public Response getReport(MaintenanceRecordRequest request){
        Response response = ValidUtil.valid(request);
        if(response != null)
            return response;
        request.setVin(request.getVin().toUpperCase());

        try {
            String key = CheyipingUtil.getRedisKey("chaboshi",request);
            String orderId = null;
            try{
                orderId = redisCache.get(key);
            }catch (Exception e){
                logger.error(e.getMessage(),e);
            }
            if(StringUtils.isEmpty(orderId)){
                response = buyReport(request);
                if(response.checkIfSuccess()){
                    orderId = String.valueOf(response.getData());
                    redisCache.set(key,orderId,config.getOrderIdCacheDays(), TimeUnit.DAYS);
                }else{
                    return response;
                }
            }

            logger.info("订单号：" + orderId );
            return getReportData(orderId);
        } catch (Exception e) {
            return ResponseFactory.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR,e.getMessage());
        }
    }
}
